axios.defaults.baseURL='http://localhost:8081'
Vue.prototype.$http = axios

/**
 * 全局获取路径中的参数
 * @returns {key: value}
 */
function parseUrl(){
    let url = location.href;
    let paramStr = url.split("?")[1];
    let obj = {};
    if (paramStr){
        let paramsArray = paramStr.split("&");
        for (let i = 0; i < paramsArray.length; i++) {
            let paramKey = paramsArray[i].split("=")[0];
            let paramValue = paramsArray[i].split("=")[1];
            obj[paramKey] = paramValue;
        }
    }
    return obj;
}


// 设置不拦截的页面
let runHtml = ["/index.html","newlist.html","rollback.html","binder.html","phoneLogin.html"];
// 获取当前浏览器地址
let url = location.href;
let isRun = false;
if (url.endsWith("/")){
    isRun = true;
}else{
    // 若包含过滤页面设置isRun为true
    for (let i = 0; i < runHtml.length; i++) {
        if (url.indexOf(runHtml[i])> -1 ){
            isRun = true;
            break;
        }
    }
}
// 对isRun取反,不在runHtml数组中的页面都进行拦截
if (!isRun){
    // 若不包含token提示“请先登录”,则跳转到登录页面
    let token = localStorage.getItem("token");
    if (!token){
        alert("请先登录！")
        location.href = "/index.html";
    }
}
// axios请求拦截器:添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
    config => {
        // 从localStorage中获取token
        let token = localStorage.getItem("token");
        // 如果token有值,我们就放到请求头里面
        if (token) {
            config.headers.token = token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    })
// 响应拦截器
axios.interceptors.response.use(function (response) {
    //对返回的数据进行操作
    let result = response.data;  // response.data 就是后端返给我们的数据
    if (!result.success && result.msg == "noLogin") { // 说明未登录,被拦截了,那么就要跳回到登陆页面
        location.href = "/index.html";
        localStorage.removeItem("token");
        localStorage.removeItem("loginUser");
    }
    return response
}, function (err) {
    return Promise.reject(err)
})